package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.system.ScenicDailyIncome;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.IScenicDailyIncomeService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * 景区每日收入Controller
 *
 * @author zjw
 * @date 2023-09-21
 */
@RestController
@RequestMapping("/system/income")
public class ScenicDailyIncomeController extends BaseController {
    @Autowired
    private IScenicDailyIncomeService scenicDailyIncomeService;

    @Data
    static class YearIncome implements Serializable {
        int year;
        double total;
        List<MonthIncome> detailData;
    }

    @Data
    static class MonthIncome implements Serializable {
        int month;
        double total;
        List<DayIncome> detailData;
    }

    @Data
    static class DayIncome implements Serializable {
        int day;
        double total;
    }

    /**
     * 查询景区每日收入列表
     */
    @PreAuthorize("@ss.hasPermi('system:income:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScenicDailyIncome scenicDailyIncome) {
        startPage();
        List<ScenicDailyIncome> list = scenicDailyIncomeService.selectScenicDailyIncomeList(scenicDailyIncome);
        return getDataTable(list);
    }

    /**
     * 获取指定景区所有的日常收入明细对象列表。
     *
     * @param scenicDailyIncome
     * @return
     */
    @GetMapping("/getAllDailyIncomeList")
    public AjaxResult getAllDailyIncomeList(ScenicDailyIncome scenicDailyIncome) {
        List<ScenicDailyIncome> allDailyIncomeList = scenicDailyIncomeService.selectScenicDailyIncomeList(scenicDailyIncome);
        List<YearIncome> yearIncomeList = new ArrayList<>();
        Map<Integer, YearIncome> yearIncomeMap = new HashMap();

        for (int i = 0; i < allDailyIncomeList.size(); i++) {
            ScenicDailyIncome dailyIncome = allDailyIncomeList.get(i);
            Date createTime = dailyIncome.getCreateTime();
            int year = createTime.getYear() + 1900;
            int month = createTime.getMonth() + 1;
            int day = createTime.getDate();

            BigDecimal dailyIncomeTotal = dailyIncome.getOrderFeeIncome().setScale(2, BigDecimal.ROUND_UP);
            DayIncome dayIncome = new DayIncome();
            dayIncome.setDay(day);
            dayIncome.setTotal(dailyIncomeTotal.doubleValue());

            YearIncome yearIncome = yearIncomeMap.get(year);
            if (Objects.nonNull(yearIncome)) {
                List<MonthIncome> yearDetailData = yearIncome.getDetailData();
                MonthIncome monthIncome = null;
                for (int i1 = 0; i1 < yearDetailData.size(); i1++) {
                    if (month == yearDetailData.get(i1).getMonth()) {
                        monthIncome = yearDetailData.get(i1);
                        break;
                    }
                }

                if (Objects.nonNull(monthIncome)) {
                    List<DayIncome> monthDetailData = monthIncome.getDetailData();
                    monthDetailData.add(dayIncome);
                    monthIncome.setTotal((new BigDecimal(monthIncome.getTotal())).add(dailyIncomeTotal).setScale(2, BigDecimal.ROUND_UP).doubleValue());
                } else {
                    //创建新的monthIncome对象
                    monthIncome = new MonthIncome();
                    List<DayIncome> monthDetailData = new ArrayList<>();
                    monthDetailData.add(dayIncome);
                    monthIncome.setMonth(month);
                    monthIncome.setTotal(dailyIncomeTotal.doubleValue());
                    monthIncome.setDetailData(monthDetailData);

                    yearDetailData.add(monthIncome);
                }
//                yearIncome.setTotal(yearIncome.getTotal() + dailyIncomeTotal);
                yearIncome.setTotal((new BigDecimal(yearIncome.getTotal())).add(dailyIncomeTotal).setScale(2, BigDecimal.ROUND_UP).doubleValue());

            } else {
                //先创建monthIncome对象
                MonthIncome newMonthIncome = new MonthIncome();
                List<DayIncome> monthDetailData = new ArrayList<>();
                monthDetailData.add(dayIncome);
                newMonthIncome.setMonth(month);
                newMonthIncome.setTotal(dailyIncomeTotal.doubleValue());
                newMonthIncome.setDetailData(monthDetailData);

                //再创建yearIncome对象
                YearIncome newYearIncome = new YearIncome();
                List<MonthIncome> yearDetailData = new ArrayList<>();
                yearDetailData.add(newMonthIncome);
                newYearIncome.setYear(year);
                newYearIncome.setTotal(dailyIncomeTotal.doubleValue());
                newYearIncome.setDetailData(yearDetailData);
                yearIncomeMap.put(year, newYearIncome);

                yearIncomeList.add(newYearIncome);
            }
        }

        return AjaxResult.success(yearIncomeList);
    }

    /**
     * 导出景区每日收入列表
     */
    @PreAuthorize("@ss.hasPermi('system:income:export')")
    @Log(title = "景区每日收入", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScenicDailyIncome scenicDailyIncome) {
        List<ScenicDailyIncome> list = scenicDailyIncomeService.selectScenicDailyIncomeList(scenicDailyIncome);
        ExcelUtil<ScenicDailyIncome> util = new ExcelUtil<ScenicDailyIncome>(ScenicDailyIncome.class);
        util.exportExcel(response, list, "景区每日收入数据");
    }

    /**
     * 获取景区每日收入详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:income:query')")
    @GetMapping(value = "/{incomeId}")
    public AjaxResult getInfo(@PathVariable("incomeId") Long incomeId) {
        return success(scenicDailyIncomeService.selectScenicDailyIncomeByIncomeId(incomeId));
    }

    /**
     * 新增景区每日收入
     */
    @PreAuthorize("@ss.hasPermi('system:income:add')")
    @Log(title = "景区每日收入", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScenicDailyIncome scenicDailyIncome) {
        return toAjax(scenicDailyIncomeService.insertScenicDailyIncome(scenicDailyIncome));
    }

    /**
     * 修改景区每日收入
     */
    @PreAuthorize("@ss.hasPermi('system:income:edit')")
    @Log(title = "景区每日收入", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScenicDailyIncome scenicDailyIncome) {
        return toAjax(scenicDailyIncomeService.updateScenicDailyIncome(scenicDailyIncome));
    }

    /**
     * 删除景区每日收入
     */
    @PreAuthorize("@ss.hasPermi('system:income:remove')")
    @Log(title = "景区每日收入", businessType = BusinessType.DELETE)
    @DeleteMapping("/{incomeIds}")
    public AjaxResult remove(@PathVariable String[] incomeIds) {
        return toAjax(scenicDailyIncomeService.deleteScenicDailyIncomeByIncomeIds(incomeIds));
    }

    /**
     * 获取指定景区历史累计总收入(只包含累计订单总费用，不包含累计订单总押金)。
     *
     * @return
     */
    @GetMapping("/getAccumulatedTotalIncome/{scenicId}")
    public AjaxResult getAccumulatedTotalIncome(@PathVariable("scenicId") Long scenicId) {
        double accumulatedTotalIncome = scenicDailyIncomeService.getAccumulatedTotalIncome(scenicId);
        return AjaxResult.success().put("accumulatedTotalIncome", accumulatedTotalIncome);
    }
}
